package com.wecloud.redis.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.wecloud.core.user.WeUser;

import redis.clients.jedis.Jedis;
@Configuration
public class RedisService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    RedisTemplate redisTemplate;
 
    public void add(String key, WeUser user) {
        Gson gson = new Gson();
        stringRedisTemplate.opsForValue().set(key, gson.toJson(user));
    }
 
    public WeUser get(String key) {
        String source = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(source)) {
            return new Gson().fromJson(source, WeUser.class);
        }
        return null;
    }
 
    public void delete(String key) {
        stringRedisTemplate.opsForValue().getOperations().delete(key);
    }
    //暂不考虑用这种方式
    public List  keys() {
    	Jedis redis = null;
    	List list = new ArrayList();
    	try {
    		redis = new Jedis("localhost", 6379);
            redis.auth("123456");
            Set<byte[]> keySet = redis.keys("*".getBytes());
            List<byte[]> listkey = new ArrayList(keySet);
            for (byte[] b : listkey) {
    			list.add(new String(b));
    		}
		} catch (Exception e) {
			
		}finally{
			redis.close();
		}
    	return list;
    }
}
